<script setup>
import { ref } from "vue";
import { pageTableData } from "@/api/orderList";
import { ElMessage, ElMessageBox } from 'element-plus';
import { cancelOrder } from "@/api/orderList";
import { completeOrder } from "@/api/orderList";

//----------- 数据定义 ---------------------------
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const orderTime = ref(null);
const completeTime = ref(null);
const status = ref(null);
const total = ref(0);

// 新增：取消原因相关
const cancelReasonDialog = ref(false); // 取消原因对话框显示状态
const cancelReason = ref(''); // 取消原因输入内容
const currentOrderId = ref(null); // 当前操作的订单ID

//----------- 选项数据 ---------------------------
const statusOptions = [
  { value: 1, label: '待付款' },
  { value: 3, label: '已付款' },
  { value: 4, label: '已发货' },
  { value: 5, label: '已取消' }
];

//----------- 方法定义 ---------------------------
const getTableData = () => {
  const query = {
    page: currentPage.value,
    pageSize: pageSize.value,
    beginTime: orderTime.value,
    endTime: completeTime.value,
    status: status.value
  };
  pageTableData(query)
      .then((res) => {
        orders.value = res.data.records;
        total.value = res.data.total;
      })
      .catch((err) => {
        console.error('获取订单数据失败:', err);
        ElMessage.error('获取订单数据失败');
      });
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getTableData();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

// 新增：打开取消原因对话框
const openCancelReasonDialog = (row) => {
  currentOrderId.value = row.id; // 记录当前订单ID
  cancelReason.value = ''; // 清空之前的输入
  cancelReasonDialog.value = true; // 显示对话框
};

// 新增：确认提交取消原因并执行取消操作
const confirmCancelWithReason = () => {
  // 验证取消原因是否为空
  if (!cancelReason.value.trim()) {
    ElMessage.warning('请输入取消原因');
    return;
  }
  const orderDTO = {
    id: currentOrderId.value,
    rejectionReason: cancelReason.value// 新增：传递取消原因
  }
  // 调用取消订单API，携带取消原因
  cancelOrder(orderDTO).then(() => {
        ElMessage.success('订单已取消');
        cancelReasonDialog.value = false; // 关闭对话框
        getTableData(); // 刷新表格数据
      })
      .catch((err) => {
        console.error('取消订单失败:', err);
        ElMessage.error('取消订单失败');
      });
};

// 完成订单 - 将状态设置为"已发货"(4)作为完成状态
const handleComplete = (row) => {
  ElMessageBox.confirm('确认订单已完成吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        completeOrder( row.id)
            .then(() => {
              ElMessage.success('订单已完成');
              getTableData();
            })
            .catch((err) => {
              console.error('完成订单失败:', err);
              ElMessage.error('完成订单失败');
            });
      })
      .catch(() => {
        ElMessage.info('已取消操作');
      });
};

// 格式化订单状态显示
const formatStatus = (status) => {
  const statusMap = {
    1: '待付款',
    3: '已付款',
    4: '已发货',
    5: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 初始化加载数据
getTableData();
</script>

<template>
  <div class="container">
    <!-- 顶部标题 -->
    <div id="title">订单管理</div>

    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="订单状态：" style="width: 300px">
        <el-select v-model="status" placeholder="请选择订单状态" clearable>
          <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间：">
        <el-date-picker
            v-model="orderTime"
            type="datetime"
            placeholder="选择下单时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="完成时间：">
        <el-date-picker
            v-model="completeTime"
            type="datetime"
            placeholder="选择完成时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
        <el-button @click="status = null; orderTime = null; completeTime = null">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品表格 -->
    <el-table :data="orders" border style="width: 100%" class="mt-20">
      <el-table-column prop="number" label="订单号" width="180" align="center" />
      <el-table-column prop="consignee" label="收货人" width="100" align="center" />
      <el-table-column prop="phone" label="电话" width="180" align="center" />
      <el-table-column prop="address" label="收货地址" width="180" align="center" />
      <el-table-column prop="status" label="订单状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag
              :type="
              row.status === 1
                ? 'warning'
                : row.status === 3
                ? 'primary'
                : row.status === 4
                ? 'info'
                : 'success'
            "
          >
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 新增：显示取消原因 -->
      <el-table-column prop="cancelReason" label="取消原因" width="120" align="center">
        <template #default="{ row }">
          <span>{{ row.cancelReason || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="180" align="center" />
      <el-table-column prop="completeTime" label="完成时间" width="180" align="center" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
              @click="openCancelReasonDialog(row)"
          type="danger"
          size="small"
          >
          取消
          </el-button>
          <el-button
              @click="handleComplete(row)"
              type="success"
              size="small"
          >
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :background="true"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 新增：取消原因对话框 -->
    <el-dialog
        v-model="cancelReasonDialog"
        title="取消订单"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="取消原因" required>
          <el-input
              v-model="cancelReason"
              type="textarea"
              placeholder="请输入取消订单的原因"
              rows="4"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelReasonDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmCancelWithReason">确认取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.container {
  padding: 24px;
  background-color: #f9fafc;
  min-height: 100vh;
}

/* 标题区域 */
#title {
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 12px;
  display: flex;
  align-items: center;
}

/* 搜索表单 */
.search-form {
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;

  display: flex;
  flex-wrap: wrap;
  gap: 16px;

  .el-form-item {
    margin-bottom: 0;

    .el-input,
    .el-select,
    .el-date-picker {
      width: 220px;

      .el-input__inner {
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        transition: all 0.3s;

        &:focus {
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          border-color: #409eff;
        }
      }
    }
  }

  .el-button {
    height: 36px;
    padding: 0 16px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
    }
  }
}

/* 表格区域 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);

  th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 500;
    padding: 12px 0;
  }

  td {
    padding: 14px 0;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(64, 158, 255, 0.03);
    }
  }

  /* 状态标签样式 */
  .el-tag {
    padding: 3px 8px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 400;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }

  /* 操作按钮 */
  .el-button {
    padding: 6px 10px;
    font-size: 12px;
    border-radius: 3px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    &.el-button--success {
      background-color: #52c41a;
      border-color: #52c41a;

      &:hover {
        background-color: #73d13d;
        border-color: #73d13d;
      }
    }

    &.el-button--danger {
      background-color: #ff4d4f;
      border-color: #ff4d4f;

      &:hover {
        background-color: #ff7875;
        border-color: #ff7875;
      }
    }
  }
}

/* 分页区域 */
.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
  padding: 12px 0;

  .el-pager li {
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
    }
  }

  .el-pagination__sizes .el-input .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);

  .el-dialog__header {
    background-color: #f5f7fa;
    padding: 16px 20px;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 24px 20px;

    .el-input {
      .el-input__inner {
        border-radius: 4px;
        height: 36px;
        line-height: 36px;
        transition: all 0.3s;

        &:focus {
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          border-color: #409eff;
        }
      }

      &.el-textarea .el-textarea__inner {
        padding: 8px 12px;
        border-radius: 4px;
        transition: all 0.3s;

        &:focus {
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          border-color: #409eff;
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

/* 响应式调整 */
@media (max-width: 992px) {
  .search-form {
    .el-form-item {
      width: 100%;
    }
  }
}
</style>